package Intermediate_algorithm.Other;

import org.junit.Test;

import java.util.ArrayDeque;
import java.util.Deque;

public class _02逆波兰表达式求值 {

    @Test
    public void test() {
        System.out.println(evalRPN(new String[]{"10","6","9","3","+","-11","*","/","*","17","+","5","+"}));
    }

    //栈
    //ps: Integer.parseInt() 将String转换为int
    // 善于运用Integer和String的方法
    public int evalRPN(String[] tokens) {
        Deque<Integer> stack = new ArrayDeque<>();
        for (String token : tokens) {
            if (token.equals("+")) {
                stack.push(stack.pop() + stack.pop());
            }else if (token.equals("-")) {
                Integer pop1 = stack.pop();
                Integer pop2 = stack.pop();
                stack.push(pop2 - pop1);
            }else if (token.equals("*")) {
                stack.push(stack.pop() * stack.pop());
            }else if (token.equals("/")) {
                Integer pop1 = stack.pop();
                Integer pop2 = stack.pop();
                stack.push(pop2 / pop1);
            }else {
                stack.push(Integer.parseInt(token));
            }
        }
        return stack.pop();
    }

}
